<template>
  <view class="container">
	  <view class="no-data" v-show="noDataFlag">
	  	<u-empty text="暂无数据" mode="favor"></u-empty>
	  </view>
    <view class="order-list">
      <view class="order-item" v-for="(order, index) in orders" :key="index">
        <view class="order-info">
          <view class="header">
            <text class="order-title">{{ order.serviceCategoryName }}</text>
			<!--   -->
            <view class="order-status">{{ getStatusText(order.status) }}</view>
          </view>
          <text class="order-time">上门时间：{{ formatDateTime(order.reserveTime) }}</text></br>
          <text class="order-address">服务地址：{{ order.orderAddress }}</text>
       <!--   <view class="order-distance">
            <text>服务地点距离: {{ order.distance }}km</text>
            <navigator url="/pages/location/location" class="map-link">查看地图</navigator>
          </view> -->
        </view>
        <view class="order-action">
          <!-- <text class="order-price">已支付：<text class="price">{{ order.servicePrice }}</text></text> -->
         <button class="order-btn" @click="cancelOrder(order)" type="warn">取消</button>
		  <button class="order-btn" @click="confirmOrder(order)" type="primary">接单</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orders: [],              // 订单列表
      pageNum: 1,              // 当前页码
      tabs: [],                // 订单筛选选项卡
      currentTab: 0,           // 当前选中 tab 索引
      loadingState: '',        // 加载状态标识
      noDataFlag: false        // 是否显示“暂无数据”的标记
    };
  },
  onLoad(option) {
    if (!this.isLogin()) {
      this.loginPage();
      return;
    }
    // this.DispatchPools();   // 获取订单池信息
    this.getToken();        // 获取 Token
  },
  onShow() {
    this.DispatchPools();   // 显示页面时刷新订单池信息
  },
  onReachBottom() {
    this.nextPage();        // 滑动到底部时加载下一页数据
  },
  onPullDownRefresh() {
    this.refreshData();     // 下拉刷新时重置数据
    uni.stopPullDownRefresh();
  },
  methods: {
    getStatusText(status) {
      return status === 'ASSIGNED' ? '未接单' : '已接单';
    },
    getToken() {
      this.$u.get('/auth/getToken', { scene: 'orderList' }).then(res => {
        if (res.data) {
          this.checkToken = res.data;
        }
      });
    },
    DispatchPools() {
      if (this.pageNum === 1) {
        this.orders = [];    // 重置订单数据
      }

      const queryParam = {
        pageSize: 10,
        currentPage: this.pageNum,
      };

      const cv = this.tabs[this.currentTab]?.value;  // 使用可选链获取当前筛选条件
      if (cv) queryParam.status = cv;

      this.loadingState = 'loading';   // 设置加载状态

      this.$u.get('/order/worker/getDispatchPool', queryParam)
        .then(res => {
          if (res && res.data) {
            if (res.data.length === 0) {
              this.noDataFlag = true;       // 设置无数据标识
              this.loadingState = 'nomore'; // 设置无更多数据的加载状态
            } else {
              this.orders = [...this.orders, ...res.data]; // 追加数据
              this.loadingState = 'loadmore'; // 重置加载状态
            }
          }else if (res.code == 500){
			  uni.showToast({
			    title: res.msg,
			    icon: 'none'
			  });
		  }
        })
        .catch(err => {
          console.error("获取订单池数据时出错:", err);
          this.loadingState = 'loadmore'; // 出错后恢复加载状态
        });
    },
    cancelOrder(order) {
      if (!order || !order.orderNum) {
        uni.showToast({ title: '订单信息错误', icon: 'none' });
        return;
      }
      this.$u.post(`/order/worker/rejectOrder?orderNum=${order.orderNum}`)
        .then(res => {
          uni.showToast({ title: res ? '取消成功！' : '取消失败！', icon: res ? 'success' : 'none' });
          this.DispatchPools(); // 刷新订单池
        })
        .catch(err => {
          uni.showToast({ title: '取消出错！', icon: 'none' });
          console.error(err);
          this.DispatchPools(); // 错误后也刷新订单池
        });
    },
    nextPage() {
      if (this.loadingState === 'nomore') return; // 若已无更多数据则不继续请求
      this.pageNum += 1;       // 页码递增
      this.DispatchPools();     // 获取下一页订单数据
    },
    confirmOrder(order) {
      if (!order || !order.orderNum) {
        uni.showToast({ title: '订单信息错误', icon: 'none' });
        return;
      }
      this.$u.post(`/order/worker/acceptOrder?orderNum=${order.orderNum}`)
        .then(res => {
          uni.showToast({ title: res ? '接单成功！' : '接单失败！', icon: res ? 'success' : 'none' });
          this.DispatchPools(); // 刷新订单池
        })
        .catch(err => {
          uni.showToast({ title: '接单出错！', icon: 'none' });
          console.error(err);
          this.DispatchPools(); // 错误后也刷新订单池
        });
    },
    formatDateTime(isoString) {
      const date = new Date(isoString);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      return `${year}年-${month}月-${day}日 ${hours}点`;
    },
    refreshData() {
      this.pageNum = 1;           // 重置页码
      this.loadingState = 'loading';
      this.DispatchPools();       // 刷新数据
    },
    isLogin() {
      const tokenValue = uni.getStorageSync('tokenValue');
      return tokenValue != null && tokenValue !== '';
    },
    switchTab(index) {
      this.currentTab = index;    // 切换 tab
      this.refreshData();         // 刷新数据
    },
  }
};
</script>



<style>
.container {
  padding: 15px;
  /* background-color: #f7f7f7; */
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.order-item {
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  border: 1px solid #e0e0e0;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.order-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.order-status {
  background-color: #e0f7fa;
  color: #007bff;
  padding: 5px 10px;
  border-radius: 12px;
  font-size: 12px;
}

.order-time,
.order-address,
.order-distance {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.map-link {
  color: #007bff;
  text-decoration: underline;
}

.order-action {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.order-price {
  font-size: 16px;
}

.price {
  color: #ff4d4f;
  font-weight: bold;
}

.order-btn {
	margin: 0;
  color: #fff;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.order-btn:hover {
  background-color: #0056b3;
}
.no-data {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 400rpx;
		background-color: white;
	}
</style>
